using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WMS.Api.Application.Commands;
using WMS.Common;
using WMS.Common.Dtos;
using WMS.Domain;
using WMS.Infrastructure;

namespace WMS.Api.Application.CommandHandlers
{
    /// <summary>
    /// 获取菜单项列表命令处理程序
    /// </summary>
    public class GetMenuItemCommandHandler : IRequestHandler<GetMenuItemCommand, ApiResult<List<MenuItem>>>
    {
        private readonly MyDBContext _dbContext;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext">数据库上下文</param>
        public GetMenuItemCommandHandler(MyDBContext dbContext)
        {
            _dbContext = dbContext;
        }

        /// <summary>
        /// 处理获取菜单项列表命令
        /// </summary>
        /// <param name="request">请求命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>菜单项列表</returns>
        public async Task<ApiResult<List<MenuItem>>> Handle(GetMenuItemCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 获取用户角色
                var userRoles = await _dbContext.RoleUser
                    .Where(ru => ru.UserId == request.UserId)
                    .Select(ru => ru.RId)
                    .ToListAsync(cancellationToken);

                if (userRoles.Count == 0)
                {
                    return new ApiResult<List<MenuItem>>("用户没有分配角色")
                    {
                        code = StatusCodeEnum.ParamError,
                        isSuc = false
                    };
                }

                // 获取角色权限
                var permissionIds = await _dbContext.RolePermission
                    .Where(rp => userRoles.Contains(rp.RId))
                    .Select(rp => rp.PerId)
                    .Distinct()
                    .ToListAsync(cancellationToken);

                // 获取所有权限
                var permissions = await _dbContext.Permission
                    .Where(p => permissionIds.Contains(p.Pid))
                    .ToListAsync(cancellationToken);
                
                // 获取根菜单项（父级ID为0的菜单项）
                var rootPermissions = permissions.Where(p => p.ParentId == 0).ToList();
                
                // 转换为菜单项
                var menuItems = new List<MenuItem>();
                foreach (var permission in rootPermissions)
                {
                    var menuItem = ConvertToMenuItem(permission);
                    
                    // 递归获取子菜单
                    menuItem.Children = GetChildrenMenuItems(permissions, permission.Pid);
                    
                    menuItems.Add(menuItem);
                }
                
                return new ApiResult<List<MenuItem>>("获取菜单成功")
                {
                    code = StatusCodeEnum.Ok,
                    data = menuItems,
                    isSuc = true
                };
            }
            catch (System.Exception ex)
            {
                return new ApiResult<List<MenuItem>>("获取菜单失败：" + ex.Message)
                {
                    code = StatusCodeEnum.ParamError,
                    isSuc = false
                };
            }
        }

        /// <summary>
        /// 将权限转换为菜单项
        /// </summary>
        /// <param name="permission">权限</param>
        /// <returns>菜单项</returns>
        private MenuItem ConvertToMenuItem(Permission permission)
        {
            return new MenuItem
            {
                Id = permission.Pid,
                Title = permission.PName,
                Icon = permission.Icon,
                Path = permission.RoutePath,
                Name = permission.PName,
                FilePath = permission.FilPath,
                ParentId = permission.ParentId
            };
        }

        /// <summary>
        /// 获取子菜单项
        /// </summary>
        /// <param name="permissions">所有权限</param>
        /// <param name="parentId">父级ID</param>
        /// <returns>子菜单项列表</returns>
        private List<MenuItem> GetChildrenMenuItems(List<Permission> permissions, int parentId)
        {
            var childPermissions = permissions.Where(p => p.ParentId == parentId).ToList();
            var childMenuItems = new List<MenuItem>();
            
            foreach (var childPermission in childPermissions)
            {
                var childMenuItem = ConvertToMenuItem(childPermission);
                childMenuItem.Children = GetChildrenMenuItems(permissions, childPermission.Pid);
                childMenuItems.Add(childMenuItem);
            }
            
            return childMenuItems;
        }
    }
} 